﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EnterpriseFund.Common;
using System.Data;
using DevExpress.Web.Mvc;

namespace EnterpriseFund.Controllers
{
        [OutputCache(Duration = 0, VaryByParam = "none")]
    public class TaxAuditPolicyEvalController : Common.AdminBaseController
    {
        //
        // GET: /TaxAuditPolicyEval/ 

        [AuthorityActionFilter("m_TaxAuditPolicyEval", Order = 1)]
        [LogPageActionFilter("政策鉴定", Order = 2)]
        public ActionResult Index()
        {
            string strwhere = " FStatus='1' ";
            List<Model.TaxAuditForm> taxAuditFormList = new List<Model.TaxAuditForm>();
            taxAuditFormList = GetTaxAuditFormListList(strwhere, 1);
            BLL.AllowanceClass allowanceClassBLL = new BLL.AllowanceClass();
            ViewData["AllowanceClassList"] = allowanceClassBLL.GetModelList("");
            return View(taxAuditFormList);
        }

        public ActionResult TaxAuditPolicyEvalListPartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string callbackArg = DevExpressHelper.CallbackArgument;

            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }
            string strwhere = " FStatus='1' ";


            string FStatus = Request.Params["FStatus"];
            string NSRBM = Request.Params["NSRBM"];
            string FAllowanceClassNo = Request.Params["FAllowanceClassNo"];
            if (FStatus != "")
            {
                if (FStatus == "1")
                {
                    strwhere += " and FIsReturn = 'N'";
                }
                else
                {
                    strwhere += " and FIsReturn = 'Y'";
                }
            }
            if (NSRBM != "" && NSRBM != null)
            {
                strwhere += " and (NSRBM like '%" + NSRBM + "%' or NSRMC like '%" + NSRBM + "%')";
            }

            if (FAllowanceClassNo != "")
            {
                strwhere += " and FAllowanceClassNo='" + FAllowanceClassNo + "'";
            }
            //string FEnterprisePropNo = Request.Params["FEnterprisePropNo"];
            //string FFinancePropNo = Request.Params["FFinancePropNo"];
            //string IsNoFull = Request.Params["IsNoFull"];

            BLL.TaxAuditForm taxAuditFormBLL = new BLL.TaxAuditForm();
            List<Model.TaxAuditForm> taxAuditFormList = new List<Model.TaxAuditForm>();
            taxAuditFormList = GetTaxAuditFormListList(strwhere, pageIndex);
            return PartialView("TaxAuditPolicyEvalListPartial", taxAuditFormList);
        }

        /// <summary>
        /// 获取定义的工作时间数据
        /// </summary>
        /// <param name="strWhere">查询条件</param>
        /// <param name="pageIndex">第几页</param>
        /// <returns>查询出来的数据</returns>
        private List<Model.TaxAuditForm> GetTaxAuditFormListList(string strWhere, int pageIndex)
        {
            BLL.Common commonBll = new BLL.Common();
            BLL.TaxAuditForm taxAuditFormBLL = new BLL.TaxAuditForm();
            string fiedls = "FTaxAuditId";
            int total;
            DataSet ds = commonBll.GetListByPage("fund.[fn_TaxAuditForm](" + OperateSession.get(GlobalConstant.PARAM_SYSYEAR) + ")", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, strWhere, "FTaxAuditId", out total);
            List<Model.TaxAuditForm> taxAuditFormList = taxAuditFormBLL.DataTableToList(ds.Tables[0]);
            List<Model.TaxAuditForm> taxAuditFormAllList = new List<Model.TaxAuditForm>();
            total = taxAuditFormBLL.GetRecordCount(strWhere, OperateSession.get(GlobalConstant.PARAM_SYSYEAR));
            int pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                taxAuditFormAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (taxAuditFormList.Count > i)
                {
                    taxAuditFormAllList[((pageIndex - 1) * pageRowSize) + i] = taxAuditFormList[i];
                }
            }

            return taxAuditFormAllList;
        }
      
        public ActionResult TaxAuditPolicyEvalSave()
        {
            try
            {
                string noList = Fetch.Post("noList");
                string[] noArr = noList.Split(',');

                List<Model.TaxAuditPolicyEval> l = new List<Model.TaxAuditPolicyEval>();
                foreach (string no in noArr)
                {
                    Model.TaxAuditPolicyEval t = new Model.TaxAuditPolicyEval();
                    t.FAllowanceType = Fetch.Post(no + "type");
                    t.FAllowanceAmount = decimal.Parse(Fetch.Post(no + "txtFAllowanceAmount") == "" ? "0" : (decimal.Parse(Fetch.Post(no + "txtFAllowanceAmount")) * 10000).ToString());
                    t.FBaseAmount = decimal.Parse(Fetch.Post(no + "txtbase") == "" ? "0" : Fetch.Post(no + "txtbase"));
                    t.FInnerRate = decimal.Parse(Fetch.Post(no + "txtrateIn") == "" ? "0" : Fetch.Post(no + "txtrateIn"))/100;
                    t.FOuterRate = decimal.Parse(Fetch.Post(no + "txtrateOut") == "" ? "0" : Fetch.Post(no + "txtrateOut"))/100;
                    t.FPolicyID = Fetch.Post(no + "FPolicyID");
                    t.FTaxAuditId = Fetch.Post("hidFTaxAuditId");
                    t.FTaxClassAllowanceNo = no;
                    t.FYear = decimal.Parse(Fetch.Post("hidFYear"));

                    switch (Fetch.Post("hidFStatus"))
                    {
                        case "open":
                            t.FStatus = "1";
                            break;
                        case "Save":
                            t.FStatus = "0";
                            break;
                    }

                    if (Fetch.Post("hidFIsByTaxFinanceProp") == "Y")
                    {
                        t.FFinancePropNo = Fetch.Post(no + "FinanceProp");
                    }
                    else
                    {
                        t.FFinancePropNo = DevExpress.Web.Mvc.ComboBoxExtension.GetValue<string>("FFinancePropNo");
                    }
                    l.Add(t);
                }

                Model.TaxAuditForm ta = new Model.TaxAuditForm();
                ta.FTaxAuditId = Fetch.Post("hidFTaxAuditId");
                ta.FNewEnterprisePropNo = DevExpress.Web.Mvc.ComboBoxExtension.GetValue<string>("FEnterprisePropNo");
                if (Fetch.Post("hidFIsByTaxFinanceProp") == "N")
                {
                    ta.FNewFinancePropNo = DevExpress.Web.Mvc.ComboBoxExtension.GetValue<string>("FFinancePropNo");
                }
                else
                {
                    if (l.Count > 0)
                    {
                        ta.FNewFinancePropNo = l[0].FFinancePropNo;
                    }
                }
                ta.FPolicyNote = Fetch.Post("FPolicyNote");

                switch (Fetch.Post("hidFStatus"))
                {
                    case "open":
                        ta.FStatus = "2";
                        ta.FIsReturn = "N";
                        break;
                    case "Save":
                        ta.FStatus = "1";
                        ta.FIsReturn = "N";
                        break;
                    case "Return":
                        ta.FStatus = "0";
                        ta.FIsReturn = "Y";
                        break;
                }
                ViewData["FStatus"] = Fetch.Post("hidFStatus");
                BLL.TaxAuditPolicyEval tBLL = new BLL.TaxAuditPolicyEval();
                tBLL.SaveAdd(l, ta);
                ViewData["jsAlert"] = "操作成功";
                if (Fetch.Post("hidFStatus") == "open")
                {
                    WorkFlow("t_TaxAuditForm", "20", ta.FTaxAuditId, "open", "");
                }
            }
            catch(Exception ex )
            {
                ViewData["jsAlert"] = ex.Message.ToString();
            }
            
            return TaxAuditPolicyEvalEdit(Fetch.Post("hidFTaxAuditId"),"");
        }

        public string Return(string taxAuditId)
        {
            try
            {
                Model.TaxAuditForm t = new Model.TaxAuditForm();
                t.FStatus = "0";
                t.FTaxAuditId = taxAuditId;
                BLL.TaxAuditForm tBLL = new BLL.TaxAuditForm();
                tBLL.UpdateStatus(t, "0");
                return "ok";
            }
            catch
            {
                return "error";
            }
        }

        public ActionResult YTaxAuditPolicyEvalEdit(string taxAuditId, string FNewEnterprisePropNo)
        {
            BLL.TaxAuditForm taxAuditFormBLL = new BLL.TaxAuditForm();
            Model.TaxAuditForm tAF = taxAuditFormBLL.GetModel(taxAuditId);
            BLL.DJ_NSRXX DJ_NSRXXBLL = new BLL.DJ_NSRXX();
            BLL.TaxAuditPolicyEval b = new BLL.TaxAuditPolicyEval();
            List<Model.TaxAuditPolicyEval> tle = b.GetModelList(" a.FTaxAuditId='" + taxAuditId + "'");

            Model.DJ_NSRXX DJ_NSRXXModel = DJ_NSRXXBLL.GetModel(tAF.NSRDZDAH, tAF.FYear.ToString());

            tAF.NSRMC = DJ_NSRXXModel.NSRMC;

            tAF.NSRBM = DJ_NSRXXModel.NSRBM;

            BLL.EnterpriseProp enterprisePropBLL = new BLL.EnterpriseProp();

            ViewData["EnterprisePropList"] = enterprisePropBLL.GetModelList("");

            if (FNewEnterprisePropNo != "" && FNewEnterprisePropNo != null)
            {
                tAF.FNewEnterprisePropNo = FNewEnterprisePropNo;
                tAF.FNewFinancePropNo = "";
            }

            Model.EnterpriseProp en = enterprisePropBLL.GetModel(tAF.FNewEnterprisePropNo);
            ViewData["FIsByTaxFinanceProp"] = en.FIsByTaxFinanceProp;
            BLL.FinanceProp financePropBLL = new BLL.FinanceProp();

            ViewData["FinancePropList"] = financePropBLL.GetSelectList(tAF.FNewEnterprisePropNo, tAF.FYear.ToString());

            BLL.TaxAuditAdjust taxAuditAdjustBLL = new BLL.TaxAuditAdjust();

            DataSet ds = taxAuditAdjustBLL.GetListForPolicy(taxAuditId);

            DataSet yDs = taxAuditAdjustBLL.GetListForYearDataShow(tAF.NSRDZDAH.ToString(), (tAF.FYear - 1).ToString());
            DataTable dt = new DataTable();

            dt = SetYPolicyData(ds.Tables[0], tle, tAF.FYear.ToString(), yDs.Tables[0]);

            for (int i = 0; i < dt.Rows.Count; i++) 
            {
                if (dt.Rows[i]["FFinancePropNo"].ToString() == "")
                {
                    dt.Rows[i]["FFinancePropNo"] = tAF.FNewFinancePropNo;
                }
            }

            ViewData["sDt"] = dt;
             
            ViewData["FYear"] = tAF.FYear.ToString();

            BLL.AllowanceClass allowanceClassBLL = new BLL.AllowanceClass();
            ViewData["AllowanceClassList"] = allowanceClassBLL.GetModelList("");

            return View("YTaxAuditPolicyEvalEdit", tAF);
        }

        public ActionResult TaxAuditPolicyEvalEdit(string taxAuditId, string FNewEnterprisePropNo)
        { 
            OperateSession.del("xzSupportPolicy");

            BLL.TaxAuditForm taxAuditFormBLL = new BLL.TaxAuditForm();
            Model.TaxAuditForm tAF = taxAuditFormBLL.GetModel(taxAuditId);
            BLL.DJ_NSRXX DJ_NSRXXBLL = new BLL.DJ_NSRXX();
            BLL.TaxAuditPolicyEval b = new BLL.TaxAuditPolicyEval();
            List<Model.TaxAuditPolicyEval> tle = b.GetModelList(" a.FTaxAuditId='" + taxAuditId + "'");

            Model.DJ_NSRXX DJ_NSRXXModel = DJ_NSRXXBLL.GetModel(tAF.NSRDZDAH, tAF.FYear.ToString());

            tAF.NSRMC = DJ_NSRXXModel.NSRMC;

            tAF.NSRBM = DJ_NSRXXModel.NSRBM;

            BLL.EnterpriseProp enterprisePropBLL = new BLL.EnterpriseProp();

            ViewData["EnterprisePropList"] = enterprisePropBLL.GetModelList("");

           

            BLL.TaxAuditAdjust taxAuditAdjustBLL = new BLL.TaxAuditAdjust();

            DataSet ds = taxAuditAdjustBLL.GetListForPolicy(taxAuditId);

            DataSet yDs = taxAuditAdjustBLL.GetListForYearDataShow(tAF.NSRDZDAH.ToString(), (tAF.FYear - 1).ToString());
            DataTable dt = new DataTable();

            if (FNewEnterprisePropNo != "" && FNewEnterprisePropNo != null)
            {
                tAF.FNewEnterprisePropNo = FNewEnterprisePropNo;
                tAF.FNewFinancePropNo = "";
            }

            Model.EnterpriseProp en = enterprisePropBLL.GetModel(tAF.FNewEnterprisePropNo);
            ViewData["FIsByTaxFinanceProp"] = en.FIsByTaxFinanceProp;
            BLL.FinanceProp financePropBLL = new BLL.FinanceProp();

            ViewData["FinancePropList"] = financePropBLL.GetSelectList(tAF.FNewEnterprisePropNo, tAF.FYear.ToString());


            if (tle.Count > 0)
            {
                dt = SetSavePolicyData(ds.Tables[0], tle, tAF.FYear.ToString(), yDs.Tables[0], tAF.FNewEnterprisePropNo);
            }
            else
            {
                BLL.YGZAllowance YGZAllowanceBLL = new BLL.YGZAllowance();
                List<Model.YGZAllowance> YGZAllowanceList = YGZAllowanceBLL.GetModelList("FYear=" + tAF.FYear + " and NSRDZDAH= " + tAF.NSRDZDAH);
                dt = GetPolicyData(ds.Tables[0], yDs.Tables[0], tAF.FYear.ToString(), tAF.FNewEnterprisePropNo, YGZAllowanceList);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dt.Rows[i]["FFinancePropNo"] = tAF.FNewFinancePropNo;
                }
            }

            ViewData["sDt"] = dt;

            ViewData["FYear"] = tAF.FYear.ToString();

            BLL.AllowanceClass allowanceClassBLL = new BLL.AllowanceClass();
            ViewData["AllowanceClassList"] = allowanceClassBLL.GetModelList("");

            return View("TaxAuditPolicyEvalEdit", tAF);
        }

      

        public string EditPolicy(string fpolicyID, string fyear, string se, string bases)
        {
            BLL.SupportPolicy spBLL = new BLL.SupportPolicy();
            Model.SupportPolicy s = spBLL.GetModel(fpolicyID, decimal.Parse(fyear));
            DataTable cDt = GetComputeExpressionDT();
            DataRow cDr = cDt.NewRow();
            cDr["se"] = se;
            cDr["base"] = (bases == "" ? 0 : decimal.Parse(bases));
            cDr["rateIn"] = (s.FInnerRate == null ? 0 : s.FInnerRate);
            cDr["rateOut"] = (s.FOuterRate == null ? 0 : s.FOuterRate);
            cDt.Rows.Add(cDr);
            cDt.Columns["zcjd"].Expression = s.FComputeExpression;
            if (cDt.Rows[0]["zcjd"] != null && cDt.Rows[0]["zcjd"].ToString() != "")
            {
                return (decimal.Parse(cDt.Rows[0]["zcjd"].ToString())) + "||" + (s.FInnerRate == null ? 0 : decimal.Round(decimal.Parse(s.FInnerRate.ToString())*100,0)) + "||" + (s.FOuterRate == null ? 0 : decimal.Round(decimal.Parse(s.FOuterRate.ToString())*100,0)) + "||" + s.FIsEvalBase;
            }
            else
            {
                return "0||" + (s.FInnerRate == null ? 0 : decimal.Round(decimal.Parse(s.FInnerRate.ToString())*100,0)) + "||" + (s.FOuterRate == null ? 0 : decimal.Round(decimal.Parse(s.FOuterRate.ToString())*100,0)) + "||" + s.FIsEvalBase;
            }
        }


        public decimal ComputePolicy(string fpolicyID, string fyear, string se, string bases, string FInnerRate, string FOuterRate)
        {
            BLL.SupportPolicy spBLL = new BLL.SupportPolicy();
            Model.SupportPolicy s = spBLL.GetModel(fpolicyID, decimal.Parse(fyear));
            DataTable cDt = GetComputeExpressionDT();
            DataRow cDr = cDt.NewRow();
            cDr["se"] = se;
            cDr["base"] = (bases == "" ? 0 : decimal.Parse(bases));
            cDr["rateIn"] = (FInnerRate == "" ? 0 : decimal.Parse(FInnerRate)/100);
            cDr["rateOut"] = (FOuterRate == "" ? 0 : decimal.Parse(FOuterRate)/100);
            cDt.Rows.Add(cDr);
            cDt.Columns["zcjd"].Expression = s.FComputeExpression;
            if (cDt.Rows[0]["zcjd"] != null && cDt.Rows[0]["zcjd"].ToString() != "")
            {
                return decimal.Parse(cDt.Rows[0]["zcjd"].ToString());
            }
            else
            {
                return 0;
            }
        }

        public DataTable SetSavePolicyData(DataTable dt, List<Model.TaxAuditPolicyEval> tl, string y, DataTable yDt, string EnterprisePropNo)
        {
            dt.Columns.Add("FPolicyID");
            dt.Columns.Add("FAllowanceAmount");
            dt.Columns.Add("base");
            dt.Columns.Add("rateIn");
            dt.Columns.Add("rateOut");
            dt.Columns.Add("FIsEvalBase");
            dt.Columns.Add("FIsPolicy");
            dt.Columns.Add("FFinancePropNo");
            dt.Columns.Add("FAllowanceType");

            foreach (DataRow dr in dt.Rows)
            {
                if (dr["se"] != null && dr["se"].ToString() != "")
                {
                    dr["se"] = decimal.Round(decimal.Parse(dr["se"].ToString()), 0);
                }
            }


            BLL.SupportPolicy sBLL = new BLL.SupportPolicy();
            List<Model.SupportPolicy> sl = sBLL.GetModelList(" sp.FYear=" + y);
            List<Model.SupportPolicy> ssl = new List<Model.SupportPolicy>();

            DataTable rDt = GetRuleExpressionDT(dt, y);///转换数据格式

            DataTable cDt = GetComputeExpressionDT();///获取公式判断数据格式
            foreach (Model.SupportPolicy s in sl)
            {
                if (s.FEnterprisePropNo == EnterprisePropNo)
                {
                    s.FRuleExpression = s.FRuleExpression.Replace("&&", " and ");
                    s.FRuleExpression = s.FRuleExpression.Replace("||", " or ");
                    DataRow[] rdrl = rDt.Select(s.FRuleExpression);///条件匹配
                    DataRow[] yDrl = yDt.Select("FTaxClassAllowanceNo='" + s.FTaxClassAllowanceNo + "'");///查询上年度数据 做基数使用
                    if (rdrl.Count() > 0)
                    {
                        ssl.Add(s);///加入匹配政策
                    }
                }
            }

            ViewData["xzSupportPolicy"] = ssl;

            foreach (Model.TaxAuditPolicyEval t in tl)
            {
                Model.SupportPolicy s = sBLL.GetModel(t.FPolicyID, decimal.Parse(y));

                DataRow[] dtrl = dt.Select("FTaxClassAllowanceNo='" + t.FTaxClassAllowanceNo + "'");
                if (dtrl.Count() > 0)
                {
                    dtrl[0]["FAllowanceType"] = t.FAllowanceType;

                    dtrl[0]["FAllowanceAmount"] = t.FAllowanceAmount == null ? 0 : decimal.Parse(t.FAllowanceAmount.ToString()) / 10000;

                    if (t.FBaseAmount != null)
                    {
                        dtrl[0]["base"] = decimal.Round(decimal.Parse(t.FBaseAmount.ToString()),0);
                    }

                    dtrl[0]["rateIn"] = decimal.Round(decimal.Parse(t.FInnerRate.ToString()) * 100,2);

                    dtrl[0]["rateOut"] = decimal.Round(decimal.Parse(t.FOuterRate.ToString()) * 100,2);

                    dtrl[0]["FFinancePropNo"] = t.FFinancePropNo;

                    if (s != null)
                    {
                        dtrl[0]["FIsEvalBase"] = s.FIsEvalBase;
                    }

                    dtrl[0]["FPolicyID"] = t.FPolicyID;
                }
            }
            //string noList = "";
            //List<string> str = new List<string>();
            for (int z = 0; z < dt.Rows.Count; z++)
            {
                List<Model.SupportPolicy> SupportPolicyList = (from nm in ssl where nm.FTaxClassAllowanceNo == dt.Rows[z]["FTaxClassAllowanceNo"].ToString() select nm).ToList();
                if (SupportPolicyList.Count > 0)
                {
                    dt.Rows[z]["FIsPolicy"] = "Y";
                }
                else
                {
                    dt.Rows[z]["FIsPolicy"] = "N";
                    dt.Rows[z]["FIsEvalBase"] = "N";
                }
            }

            //ViewData["noList"] = noList;

            //DataTable r = (from nm in dt.AsEnumerable() where str.Contains(nm.Field<string>("FTaxClassAllowanceNo")) select nm).CopyToDataTable();

            return dt;
        }

        public DataTable SetYPolicyData(DataTable dt, List<Model.TaxAuditPolicyEval> tl, string y, DataTable yDt)
        {
            dt.Columns.Add("FAllowanceAmount");

            dt.Columns.Add("rateOut");

            dt.Columns.Add("FAllowanceType");

            dt.Columns.Add("FFinancePropNo");

            dt.Columns["FAllowanceType"].DefaultValue = "1";

            dt.Columns["FAllowanceAmount"].DefaultValue = 0;

            dt.Columns["rateOut"].DefaultValue = 0;

            DataTable rDt = GetRuleExpressionDT(dt, y);///转换数据格式

            BLL.SupportPolicy sBLL = new BLL.SupportPolicy();

            foreach (DataRow dr in dt.Rows)
            {
                if (dr["se"] != null && dr["se"].ToString() != "")
                {
                    dr["se"] = decimal.Round(decimal.Parse(dr["se"].ToString()), 0);
                }
            }

            foreach (Model.TaxAuditPolicyEval t in tl)
            {
               // Model.SupportPolicy s = sBLL.GetModel(t.FPolicyID, decimal.Parse(y));

                DataRow[] dtrl = dt.Select("FTaxClassAllowanceNo='" + t.FTaxClassAllowanceNo + "'");
                if (dtrl.Count() > 0)
                {
                    dtrl[0]["FAllowanceAmount"] = (t.FAllowanceAmount == null ? 0 : decimal.Parse(t.FAllowanceAmount.ToString()) / 10000);
                    if (t.FOuterRate != null)
                    {
                        dtrl[0]["rateOut"] = decimal.Round(decimal.Parse(t.FOuterRate.ToString()) * 100, 2);
                    }
                    else
                    {
                        dtrl[0]["rateOut"] = 0;
                    }
                    dtrl[0]["FFinancePropNo"] = t.FFinancePropNo;
                    dtrl[0]["FAllowanceType"] = t.FAllowanceType;
                }
            }

            

            return dt;
        }

        /// <summary>
        /// 政策鉴定过程
        /// </summary>
        /// <param name="dt">税款数据</param>
        /// <param name="yDt">上年度税款数据作为基数使用</param>
        /// <param name="y">年度</param>
        /// <returns>鉴定后数据列表</returns>
        public DataTable GetPolicyData(DataTable dt, DataTable yDt, string y, string FEnterprisePropNo, List<Model.YGZAllowance> YGZAllowanceList)
        {
            dt.Columns.Add("FPolicyID");
            dt.Columns.Add("FAllowanceAmount");
            dt.Columns.Add("base");
            dt.Columns.Add("rateIn");
            dt.Columns.Add("rateOut");
            dt.Columns.Add("FIsEvalBase");
            dt.Columns.Add("FIsPolicy"); 
            dt.Columns.Add("FFinancePropNo");
            dt.Columns.Add("FAllowanceType");


            foreach (DataRow dr in dt.Rows)
            {
                if (dr["se"] != null && dr["se"].ToString() != "")
                {
                    dr["se"] = decimal.Round(decimal.Parse(dr["se"].ToString()), 0);
                }
            }

            BLL.SupportPolicy sBLL = new BLL.SupportPolicy();

            List<Model.SupportPolicy> sl = sBLL.GetModelList(" sp.FYear=" + y);

            List<Model.SupportPolicy> ssl = new List<Model.SupportPolicy>();

            DataTable rDt = GetRuleExpressionDT(dt,y);///转换数据格式

            DataTable cDt = GetComputeExpressionDT();///获取公式判断数据格式

            foreach (Model.SupportPolicy s in sl)
            {
                if (s.FEnterprisePropNo == FEnterprisePropNo)
                {
                    s.FRuleExpression = s.FRuleExpression.Replace("&&", " and ");
                    s.FRuleExpression = s.FRuleExpression.Replace("||", " or ");


                    DataRow[] rdrl = rDt.Select(s.FRuleExpression);///条件匹配
                    DataRow[] yDrl = yDt.Select("FTaxClassAllowanceNo='" + s.FTaxClassAllowanceNo + "'");///查询上年度数据 做基数使用
                    if (rdrl.Count() > 0)
                    {
                        ssl.Add(s);///加入匹配政策

                        ///是否为普惠曾策
                        if (s.FProp == "1")
                        {
                            if (s.FTaxClassAllowanceName.Contains("营改增"))
                            {
                                decimal sum = YGZAllowanceList.Sum(z => z.FAmount);
                                rdrl[0][s.FTaxClassAllowanceNo] = decimal.Parse(rdrl[0][s.FTaxClassAllowanceNo].ToString()) - sum;
                            }
                            DataRow[] dtrl = dt.Select("FTaxClassAllowanceNo='" + s.FTaxClassAllowanceNo + "'");
                            ///判断该税种是否已相关政策
                            if (dtrl.Count() > 0)
                            {
                                DataRow cDr = cDt.NewRow();
                                if (s.FIsEvalBase == "Y")
                                {
                                    cDr["se"] = rdrl[0][s.FTaxClassAllowanceNo];
                                    cDr["base"] = (yDrl.Count() > 0 ? decimal.Round(decimal.Parse(yDrl[0]["FAdjustAmount"].ToString()),0) : 0);
                                    cDr["rateIn"] = s.FInnerRate;
                                    cDr["rateOut"] = s.FOuterRate;
                                }
                                else
                                {
                                    cDr["se"] =  decimal.Round(decimal.Parse(rdrl[0][s.FTaxClassAllowanceNo].ToString()),0);
                                    cDr["base"] = "0";
                                    cDr["rateIn"] = "0";
                                    cDr["rateOut"] = s.FOuterRate;
                                }
                                if (cDr["base"] == null || cDr["base"].ToString() == "")
                                {
                                    cDr["base"] = "0";
                                }
                                cDt.Rows.Clear();
                                cDt.Rows.Add(cDr);

                                cDt.Columns["zcjd"].Expression = s.FComputeExpression;///公式计算补贴额

                                dtrl[0]["FAllowanceAmount"] = decimal.Round((decimal.Parse(cDt.Rows[0]["zcjd"].ToString())/10000),0);

                                dtrl[0]["base"] = decimal.Round(decimal.Parse(cDt.Rows[0]["base"].ToString()),0);

                                dtrl[0]["rateIn"] = decimal.Round(decimal.Parse(cDt.Rows[0]["rateIn"].ToString())*100,0);

                                dtrl[0]["rateOut"] =decimal.Round( decimal.Parse(cDt.Rows[0]["rateOut"].ToString())*100,0);

                                dtrl[0]["FIsEvalBase"] = s.FIsEvalBase;

                                dtrl[0]["FPolicyID"] = s.FPolicyID;

                                dtrl[0]["FFinancePropNo"] = "";

                                dtrl[0]["FAllowanceType"] = "1";
                            }
                        }
                    }
                }
            }

            ViewData["xzSupportPolicy"] = ssl;
            //string noList = "";
            //List<string> str = new List<string>();
            for (int z = 0; z < dt.Rows.Count; z++)
            {
                List<Model.SupportPolicy> SupportPolicyList = (from nm in ssl where nm.FTaxClassAllowanceNo == dt.Rows[z]["FTaxClassAllowanceNo"].ToString() select nm).ToList();
                if (SupportPolicyList.Count > 0)
                {
                    dt.Rows[z]["FIsPolicy"] = "Y";
                }
                else
                {
                    dt.Rows[z]["FIsPolicy"] = "N";
                    dt.Rows[z]["FIsEvalBase"] = "N";

                }
                dt.Rows[z]["FAllowanceType"] = "1";
            }

            //ViewData["noList"] = noList;

            //DataTable r = (from nm in dt.AsEnumerable() where str.Contains(nm.Field<string>("FTaxClassAllowanceNo")) select nm).CopyToDataTable();
            
            return dt;
        }

        /// <summary>
        /// 数据格式转换装换为条件判断格式
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public DataTable GetRuleExpressionDT(DataTable dt, string y)
        {
            BLL.TaxClassAllowance tBLL = new BLL.TaxClassAllowance();
            List<Model.TaxClassAllowance> tl = tBLL.GetModelList(" FYear=" + y);
            DataTable rDt = new DataTable();
            string noList = "";
            foreach (Model.TaxClassAllowance t in tl)
            {
                rDt.Columns.Add(t.FTaxClassAllowanceNo, typeof(decimal));
            }

            DataRow rDr = rDt.NewRow();

            foreach (DataColumn dc in rDt.Columns)
            {
                DataRow[] dtrl = dt.Select(" FTaxClassAllowanceNo='" + dc.ColumnName + "'");
                if (dtrl.Count() > 0)
                {
                    rDr[dc.ColumnName] = dtrl[0]["se"];
                    if (noList != "")
                    {
                        noList += "," + dc.ColumnName;
                    }
                    else
                    {
                        noList += dc.ColumnName;
                    }
                }
                else
                {
                    rDr[dc.ColumnName] = 0;
                }
            }
            ViewData["noList"] = noList;
            rDt.Rows.Add(rDr);
            return rDt;
        }

        /// <summary>
        /// 公式判断数据格式
        /// </summary>
        /// <returns></returns>
        public DataTable GetComputeExpressionDT()
        {
            DataTable cDt = new DataTable();
            cDt.Columns.Add("se", typeof(decimal));
            cDt.Columns.Add("base", typeof(decimal));
            cDt.Columns.Add("rateIn", typeof(decimal));
            cDt.Columns.Add("rateOut", typeof(decimal));
            cDt.Columns.Add("zcjd");
            return cDt;
        }

        /// <summary>
        /// 构造显示DT的总和行
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public DataTable GetYearShowData(DataTable dt)
        {
            dt.Columns.Add("cz");

            foreach (DataRow drz in dt.Rows)
            {
                drz["cz"] = "mx";
                if (drz["FAdjustAmount"] == null && drz["FAdjustAmount"].ToString() == "")
                {
                    drz["FAdjustAmount"] = 0;
                }
            }

            dt.Columns["FAdjustAmount"].DataType = typeof(decimal);
            decimal sumse = dt.AsEnumerable().Sum(p => p.Field<decimal>("FAdjustAmount"));

            DataRow dr = dt.NewRow();
            dr["cz"] = "合计";
            dr["FAdjustAmount"] = sumse;
            dt.Rows.Add(dr);
            return dt;
        }

        public ActionResult YearDataShow(string year, string NSRDZDAH)
        {
            BLL.TaxAuditAdjust taxAuditAdjustBLL = new BLL.TaxAuditAdjust();
            DataSet ds = taxAuditAdjustBLL.GetListForYearDataShow(NSRDZDAH, year);
            ViewData["NSRDZDAH"] = NSRDZDAH;
            ViewData["year"] = year;
            return View(GetYearShowData(ds.Tables[0]));
        }

        public ActionResult YearDataShowListPartial()
        {
            return View();
        }

        public ActionResult LookEntry(string taxClassAllowanceNo, string fyear, string NSRDZDAH, string FTaxAuditId)
        {
            BLL.TaxAuditAdjust taxAuditAdjustBLL = new BLL.TaxAuditAdjust();
            BLL.TaxAuditForm taxAuditFormBLL = new BLL.TaxAuditForm();
            BLL.TaxClassAllowance taxClassAllowanceBLL = new BLL.TaxClassAllowance();
            BLL.DJ_NSRXX DJ_NSRXXBLL = new BLL.DJ_NSRXX();
            DataSet ds = new DataSet();
            if (NSRDZDAH != null && NSRDZDAH != "")
            {
                ds = taxAuditAdjustBLL.GetListForYearDataShowEntry(NSRDZDAH, fyear);

                ViewData["rq1"] = DateTime.Parse(fyear + "-01-01").ToString("yyyy-MM-dd");
                ViewData["rq2"] = DateTime.Parse(fyear + "-12-31").ToString("yyyy-MM-dd"); 
                ViewData["rq"] = DateTime.Parse(fyear + "-01-01") + "至" + DateTime.Parse(fyear + "-12-31");
                ViewData["nsrmc"] = DJ_NSRXXBLL.GetModel(decimal.Parse(NSRDZDAH), fyear).NSRMC;
                ViewData["taxClassName"] = taxClassAllowanceBLL.GetModel(decimal.Parse(fyear), taxClassAllowanceNo).FTaxClassAllowanceName;
            }
            else if (FTaxAuditId != null && FTaxAuditId != "")
            {
                Model.TaxAuditForm tAM = taxAuditFormBLL.GetModel(FTaxAuditId);
                ViewData["nsrmc"] = tAM.NSRMC;
                ViewData["taxClassName"] = taxClassAllowanceBLL.GetModel(tAM.FYear, taxClassAllowanceNo).FTaxClassAllowanceName;
                ViewData["rq1"] = tAM.RKRQ_Q.ToString("yyyy-MM-dd");
                ViewData["rq2"] = tAM.RKRQ_Z.ToString("yyyy-MM-dd"); 
                ds = taxAuditAdjustBLL.GetListForPolicyEntry(FTaxAuditId, taxClassAllowanceNo);
            }

            ds.Tables[0].Columns.Add("xh");
            int i = 1;
            foreach (DataRow r in ds.Tables[0].Rows)
            {
                r["xh"] = i;
                i++; 
            }
            BLL.HREmpl hrEmplBLL = new BLL.HREmpl();
            List<Model.TaxAuditLookEntry> taxAuditLookEntryList = new List<Model.TaxAuditLookEntry>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                Model.TaxAuditLookEntry tAE = new Model.TaxAuditLookEntry();
                tAE.se = decimal.Parse(dr["FAdjustAmount"].ToString());
                tAE.RKRQ = DateTime.Parse(dr["FAdjustDate"].ToString());
                tAE.isAdjust = dr["dataType"].ToString();
                tAE.AdjustNote = dr["FNote"].ToString();
                tAE.xh = int.Parse(dr["xh"].ToString());
                if (dr["FAdjustEmpNo"].ToString() != "")
                {
                    DataSet hrDs = hrEmplBLL.GetEmplFromViewByEmplNo(dr["FAdjustEmpNo"].ToString(), GlobalConstant.ENTITYNO);
                    if (hrDs.Tables[0].Rows.Count > 0)
                    {
                        tAE.AdjustName = hrDs.Tables[0].Rows[0]["FEmpName"].ToString();
                    }
                }
                taxAuditLookEntryList.Add(tAE);
            }

            OperateSession.addList<Model.TaxAuditLookEntry>("taxAuditPolicyEvalEntryList", taxAuditLookEntryList);
            return View(taxAuditLookEntryList);
        }


        public ActionResult LookEntryPartial()
        {
            return PartialView("LookEntryPartial", OperateSession.getList<Model.TaxAuditLookEntry>("taxAuditPolicyEvalEntryList").OrderBy(nm => nm.RKRQ));
        }

        public ActionResult YTaxAuditPolicyEvalSave()
        {
            try
            {
                string noList = Fetch.Post("noList");
                string[] noArr = noList.Split(',');

                List<Model.TaxAuditPolicyEval> l = new List<Model.TaxAuditPolicyEval>();
                foreach (string no in noArr)
                {
                    Model.TaxAuditPolicyEval t = new Model.TaxAuditPolicyEval();
                    t.FAllowanceType = Fetch.Post(no + "type");
                    t.FAllowanceAmount = decimal.Parse(Fetch.Post(no + "txtFAllowanceAmount") == "" ? "0" : (decimal.Parse(Fetch.Post(no + "txtFAllowanceAmount")) * 10000).ToString());
                    t.FOuterRate = decimal.Parse(Fetch.Post(no + "txtrateOut") == "" ? "0" : (decimal.Parse(Fetch.Post(no + "txtrateOut"))/100).ToString());
                    t.FTaxAuditId = Fetch.Post("hidFTaxAuditId");
                    t.FTaxClassAllowanceNo = no;
                    t.FYear = decimal.Parse(Fetch.Post("hidFYear"));
                    if (Fetch.Post("hidFIsByTaxFinanceProp") == "Y")
                    {
                        t.FFinancePropNo = Fetch.Post(no + "FinanceProp");
                    }
                    else
                    {
                        t.FFinancePropNo = DevExpress.Web.Mvc.ComboBoxExtension.GetValue<string>("FFinancePropNo");
                    }
                    l.Add(t);
                }

                Model.TaxAuditForm ta = new Model.TaxAuditForm();
                ta.FTaxAuditId = Fetch.Post("hidFTaxAuditId");
                ta.FNewEnterprisePropNo = DevExpress.Web.Mvc.ComboBoxExtension.GetValue<string>("FEnterprisePropNo");

                if (Fetch.Post("hidFIsByTaxFinanceProp") == "N")
                {
                    ta.FNewFinancePropNo = DevExpress.Web.Mvc.ComboBoxExtension.GetValue<string>("FFinancePropNo");
                }
                else
                {
                    if (l.Count > 0)
                    {
                        ta.FNewFinancePropNo = l[0].FFinancePropNo;
                    }
                }
                ta.FPolicyNote = Fetch.Post("FPolicyNote");

                switch (Fetch.Post("hidFStatus"))
                {
                    case "open":
                        ta.FStatus = "2";
                        ta.FIsReturn = "N";
                        break;
                    case "Save":
                        ta.FStatus = "1";
                        ta.FIsReturn = "N";
                        break;
                    case "Return":
                        ta.FStatus = "0";
                        ta.FIsReturn = "Y";
                        break;
                }
                ViewData["FStatus"] = Fetch.Post("hidFStatus");
                BLL.TaxAuditPolicyEval tBLL = new BLL.TaxAuditPolicyEval();
                tBLL.SaveAdd(l, ta);
                ViewData["jsAlert"] = "操作成功";
            }
            catch
            {
                ViewData["jsAlert"] = "ex";
            }

            return YTaxAuditPolicyEvalEdit(Fetch.Post("hidFTaxAuditId"),"");
        }
    }
}
